package data

import (
	"context"
	"database/sql"
	"geek-homework/week04/internal/biz"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

var _ biz.UserRepo = (*userRepo)(nil)

type userRepo struct {
	data     *Data
	userColl *gorm.DB
}

func NewUserRepo(data *Data) biz.UserRepo {
	return &userRepo{
		data:     data,
		userColl: data.db.Model(&User{}),
	}
}

type User struct {
	Id   int64  `gorm:"column:id"`
	Name string `gorm:"column:real_name"`
}

func (r *userRepo) GetUser(ctx context.Context, id int64) (*biz.User, error) {
	result := &User{}
	if err := r.userColl.WithContext(ctx).
		Select([]string{"id", "real_name"}).
		Where("id = ?", id).First(&result).Error; err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return &biz.User{Id: id}, nil
		}
		return nil, errors.Wrap(err, "get user")
	}
	return &biz.User{Id: result.Id, Name: result.Name}, nil
}
